package com.isecommerce.framework.util;

/**
 * Tokenizer.<br><br>
 *
 * Different from Java standard StringTokenize:
 *
 * <ul>
 * <li> StringTokenizer : ',,,' -> '' (delimiter exist only -> no data:cause parse error)
 * <li> Tokenizer : ',,,' -> ',,,' (delmiter exist only -> delimiter exist and no data)
 * <li> SPACE character is no more default delimiter.
 * </ul>
 *
 * @version 1.2.5
 * @author MinKyung, Oh
 */

public class Tokenizer {
    private String str;
    private String delimiter;

    /**
     * Default constructor with given string and delimiter.
     *
     * @param str String data.
     * @param delimiter Delimiter for tokenizing.
     */
    public Tokenizer(String str, String delimiter) {
        if(str!=null && str.length()==0)
            this.str = null;
        else
            this.str = str;
        this.delimiter = delimiter;
    }

    /**
     * Check whether more token exists or not.
     *
     * @return Exist or not.
     */
    public boolean hasMoreTokens() {
        if( str==null ) return false;
        else return true;
    }

    /**
     * Get next token.
     *
     * @return String of next token.
     */
    public String nextToken() {
        String ret = null;
        if( str==null ) return ret;

        int index = str.indexOf(delimiter);
        if(index==-1) {
            ret = str;
            str = null;
        }
        else {
            ret = str.substring(0,index);
            if(str.length()>delimiter.length())
                str = str.substring(index+delimiter.length());
            else
                str = null;
        }

        return ret;
    }

    /**
     * Get number of tokens.
     *
     * @return Number of tokens.
     */
    public int countTokens() {
        int count = 1;

        for(int i=0; i<str.length(); i++) {
            if(str.startsWith(delimiter, i)) count++;
        }

        return count;
    }
}
